import os
import sys
import time
# print(os.path.dirname(os.path.dirname(os.path.abspath(__file__))+"/../../"))
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))+"/../"))

from ServerSide.Logic.Login import LoginLogic
from nicegui import ui, app
from starlette.middleware.sessions import SessionMiddleware
from fastapi import Request
from ServerSide.Model.Stocks import StocksDal, StocksModel

app.add_middleware(SessionMiddleware, secret_key='some_random_string')


from  UserUi.Stocks import getListOfAStock,showRecommend

session_info = {}
import ServerSide.UserUi.Login
@ui.page('/')
def main(request: Request)-> None:
    print("in main")
    if 'id' in request.session:
        session_info['id']=request.session['id']
    if 'id' in session_info:
        request.session['id'] = session_info['id']
    if 'id' not in request.session and 'id' not in session_info:
        ui.label("未登录用户")
    dal = StocksDal()
    links = dal.getAllCode()
    # print(links)
    # print("links above")
    for row in links:
        # print("in reflash:",row)
        # ui.button(row.code, on_click=lambda: ui.open(url))
        ui.link(row.code, '/show/' + row.code)
    with ui.header():
        ui.button('首页', on_click=lambda: ui.open("/"))
    if 'id' not in request.session:
        with ui.right_drawer(elevated=True):
            with ui.card():
                ui.button('登录', on_click=lambda: ui.open('/loginform'))
                ui.button('注册', on_click=lambda: ui.open('/registerform'))
    else:
        with ui.right_drawer(elevated=True):
            ui.button('退出', on_click=lambda: ui.open('/logout'))
@ui.page('/loginform')
def loginform(request: Request)-> None:
    ip=(request.client.host)
    # nicegui input
    input1=ui.input(label='手机', placeholder='start typing',
             validation={'Input too long': lambda value: len(value) < 12})
    input2=ui.input(label='密码', placeholder='start typing',password=True,
             validation={'Input too long': lambda value: len(value) < 13 and len(value) >7})
    # nicegui button
    loginc=LoginLogic()
    ui.button('登录', on_click=lambda: loginc.checkLogin(input1.value, input2.value,ip,v,session_info))
    v = ui.label("")
    # dal =UserProfileDal()
    # rows = dal.findAll()
    # for row in rows:
    #     print(row.id,row.username,row.password,row.ip)

# page logout
@ui.page('/logout')
def logout(request: Request)-> None:
    session_info.clear()
    request.session.clear()

    with ui.card():
        ui.label("退出成功")
        ui.button('返回首页', on_click=lambda: ui.open("/"))

@ui.page('/del_by_code/{code}')
def del_by_code(request: Request, code: str)-> None:
    dal = StocksDal()
    dal.del_all_byDate(code)
    ui.open("/")
ui.run(port=8080)